package com.yicong.ants.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PhotoUtils {
    /**
     * 存放发送图片的目录
     */
    public static final String PICTURE_PATH = Environment.getExternalStorageDirectory() + "/zhong_shi/image/";
    /**
     * 头像压缩文件存放路径
     */
    public static final String COMPRESS_PATH = Environment.getExternalStorageDirectory() + "/zhong_shi/compress/";
    private static String imgPath = null;

    /**
     * Activity 调用相机
     */
    public static void takePhoto(Activity activity) {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, ConstantCodeUtils.TAKE_PHOTO_REQUEST_CODE);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mkLocalDir(PICTURE_PATH));//拍照得到的图片输入到该路径下
            activity.startActivityForResult(intent, ConstantCodeUtils.REQUESTCODE_CAMERA);
        }
    }

    /**
     * Fragment 调用相机
     */
    public static void takePhoto(Fragment fragment) {
        if (ContextCompat.checkSelfPermission(fragment.getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(fragment.getActivity(), new String[]{Manifest.permission.CAMERA}, ConstantCodeUtils.TAKE_PHOTO_REQUEST_CODE);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mkLocalDir(PICTURE_PATH));//拍照得到的图片输入到该路径下
            fragment.startActivityForResult(intent, ConstantCodeUtils.REQUESTCODE_CAMERA);
        }
    }

    public static String getImgPath() {
        return imgPath;
    }

    /**
     * 创建图片路径名称，并由imgPath 保存文件的路径
     */
    public static Uri mkLocalDir(String fileName) {
        File dir = new File(fileName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 为以时间为图片命名
        File imageFile = new File(dir,
            new SimpleDateFormat("yyMMddHHmmss").format(new Date())
                + ".jpg");
        imgPath = imageFile.getAbsolutePath();
        Uri imgUri = Uri.fromFile(imageFile);
        return imgUri;
    }

    public static File mkLocalFileDir(String filePath, String fileName) {
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 为以时间为图片命名
        File imageFile = new File(dir,
            fileName);
        return imageFile;
    }
}
